<template>
  <div style="background-color: #f5f6f7; width: 958px">
    <div class="base-storage-edit-storage-frame">
      <el-form :model="editForm" :rules="rules" ref="editForm"  class="base-storage-edit-storage-inputForm">
        <el-form-item label="主体名称" prop="storageName" class="el-form-item">
          <el-input v-model="editForm.storageName" placeholder="输入主体名称" maxlength="20" clearable></el-input>
        </el-form-item>
        <el-form-item label="仓储地" prop="city" class="el-form-item-right">
          <div class= "base-storage-edit-storage-city-picker">
            <el-select style="width: 160px" v-model="selectedProvince" value-key="id" clearable
                       placeholder="选择省份"
                       @change="handleProvinceChange">
              <el-option
                v-for="item in provinces"
                :key="item.id"
                :label="item.nodeName"
                :value="item">
                <span style="float: left">{{ item.nodeName }}</span>
              </el-option>
            </el-select>
            <span style="margin-left: 5px; margin-right: 5px; width: 10px; color: #e5e5e5">-</span>
            <el-select style="width: 240px" v-model="selectedCity" value-key="id" clearable
                       placeholder="选择城市" @change="handleCityChange">
              <el-option
                v-for="item in cities"
                :key="item.id"
                :label="item.nodeName"
                :value="item">
                <span style="float: left">{{ item.nodeName }}</span>
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="技术手段" prop="techType" class="el-form-item">
          <el-select class="base-storage-edit-storage-selector" v-model="editForm.techType" clearable filterable placeholder="选择技术手段">
            <el-option v-for="item in techTypeOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="冷库规模（吨）" prop="totalVolume" class="el-form-item-right">
          <el-input v-model="editForm.totalVolume" placeholder="输入冷库规模" maxlength="12" @keyup.native="verifyDecimal(editForm, 'totalVolume')" clearable></el-input>
        </el-form-item>
        <el-form-item label="历史交易量（吨）" prop="totalTradeVolume" class="el-form-item">
          <el-input v-model="editForm.totalTradeVolume" placeholder="输入历史交易量" maxlength="12" @keyup.native="verifyDecimal(editForm, 'totalTradeVolume')" clearable disabled></el-input>
        </el-form-item>
        <el-form-item label="历史交易次数" prop="totalTradeTime" class="el-form-item-right">
          <el-input v-model="editForm.totalTradeTime" placeholder="输入历史交易次数" maxlength="6" @keyup.native="verifyInteger(editForm, 'totalTradeTime')" clearable disabled></el-input>
        </el-form-item>
        <el-form-item label="历史违规次数" prop="totalViolateTime" class="el-form-item">
          <el-input v-model="editForm.totalViolateTime" placeholder="输入历史违规次数" maxlength="6" @keyup.native="verifyInteger(editForm, 'totalViolateTime')" clearable disabled></el-input>
        </el-form-item>
        <el-form-item label="MIG评级" prop="migGrade" class="el-form-item-right">
          <el-select class="base-storage-edit-storage-selector" v-model="editForm.migGrade" clearable filterable placeholder="选择MIG评级" disabled>
            <el-option v-for="item in migGradeOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <input-com :headTitle="'MIG提供参考资料'" :inputValue="this.editForm.migReference" :headSonTitle="'选填'" @getInputVal="getInputReferenceVal" :isActive="true"></input-com>
    <el-row class="base-storage-edit-storage-btnFrame">
      <el-button class="base-storage-edit-storage-btn" @click="submitForm('editForm')" type="primary">保存</el-button>
    </el-row>
  </div>
</template>
<script>
  import maValidate from 'utils/common-method/validate/index';
  import inputCom from 'components/input/baseTitleInput.vue';
  import {validateTips} from 'utils/tips';
  import PcDialog from 'components/dialog';
  export default {
    components: {
      inputCom,
      PcDialog
    },
    props: ['storageInfo'],
    data() {
      var checkVolume = (rule, value, callback) => {
        if (!value) {
          return callback();
        }
        if (value) {
          setTimeout(() => {
            if (parseFloat(value) > 999999999.99) {
              callback(new Error('输入值超出限制，可支持整数9位、小数2位\n'));
            } else {
              callback();
            }
          }, 500);
        }
      };
      return {
        initForm: JSON.stringify(this.storageInfo),
        editForm: JSON.parse(JSON.stringify(this.storageInfo)),
        rules: {
          storageName: [
            {required: true, message: validateTips.FILL_BASE_INFO, trigger: 'blur'},
            {min: 0, max: 20, message: validateTips.LESS_20, trigger: 'blur'}
          ],
          city: [
            {required: true, message: validateTips.FILL_BASE_INFO, trigger: 'blur'}
          ],
          techType: [
            {required: true, message: validateTips.FILL_BASE_INFO, trigger: 'blur'}
          ],
          totalVolume: [
            {required: true, message: validateTips.FILL_BASE_INFO, trigger: 'blur'},
            {validator: checkVolume, trigger: 'blur'}
          ]
        },
        provinces: [],
        cities: [],
        selectedProvince: '',
        selectedCity: '',
        techTypeOption: [
          {
            value: 1,
            label: '人工单据'
          }, {
            value: 2,
            label: '电子单据'
          }
        ],
        migGradeOption: [
          {
            value: 'AAA',
            label: 'AAA'
          }, {
            value: 'AA',
            label: 'AA'
          }, {
            value: 'A',
            label: 'A'
          }, {
            value: 'BBB',
            label: 'BBB'
          }, {
            value: 'BB',
            label: 'BB'
          }, {
            value: 'B',
            label: 'B'
          }, {
            value: 'C',
            label: 'C'
          }
        ]
      };
    },
    created() {
      this.editForm = JSON.parse(JSON.stringify(this.storageInfo));
      // 初始化城市数据
      this.initAddressData();
      this.selectedProvince = this.editForm.province;
      this.selectedCity = this.editForm.city;
      if (this.selectedProvince !== null && this.selectedProvince !== '') {
        let that = this;
        this.provinces.forEach(function (province, index) {
          if (province.nodeName === that.selectedProvince) {
            that.cities = province.children;
          }
        });
      }
    },
    methods: {
      // 初始化城市数据
      initAddressData() {
        let address = this.$pcLockr.get(this.$pcEnum.ADDRESS.DISTRICT); // 从浏览器中读取缓存的城市数据
        // 判断有没有缓存的城市数据， 如果有直接用， 如果没有则请求接口
        if (address) {
          this.provinces = address;
          // 去除掉多余三级城市的数据
          this.removeExcrescentData();
          return;
        }
        this.ajax({
          url: '/mdc/address/get4City',
          success: (res) => {
            let data = res.result;
            if (!data) {
              return;
            }
            this.provinces = data;
            // 去除掉多余三级城市的数据
            this.removeExcrescentData();
            // 缓存在浏览器中
            this.$pcLockr.set(this.$pcEnum.ADDRESS.DISTRICT, data);
          }
        });
      },
      removeExcrescentData() {
        // 去除掉多余三级城市的数据
        this.provinces.forEach(function (province, index) {
          if (province.children) {
            province.children.forEach(function (child, index) {
              if (child.children) {
                child.children = null;
              }
            });
          }
        });
      },
      // 选择省份变化时的回调函数
      handleProvinceChange(val) {
        this.cities = val.children;
        this.selectedProvince = val.nodeName;
        this.selectedCity = '';
      },
      // 选择城市变化时的回调函数
      handleCityChange(val) {
        this.selectedCity = val.nodeName;
      },
      // 校验整数
      verifyInteger(val, prop) {
        maValidate.verifyInteger(val, prop);
      },
      // 校验小数
      verifyDecimal(val, prop) {
        maValidate.verifyDecimal(val, prop);
      },
      // 获取MIG提供参考资料的输入内容
      getInputReferenceVal(val) {
        this.editForm.migReference = val;
      },
      // 点击提交按钮
      submitForm(formName) {
        this.editForm.province = this.selectedProvince;
        this.editForm.city = this.selectedCity;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.commitForm();
          } else {
            return false;
          }
        });
      },
      // 请求后端接口
      commitForm() {
        // 内容检查：判断提交前后有无内容变化
        if (this.initForm === JSON.stringify(this.editForm)) {
          this.errorTip('内容没有任何变化，请确认');
          return;
        }
        var that = this;
        this.ajax({
          type: 'POST',
          url: '/malisk/server/base/saveStorage',
          data: {
            id: that.editForm.id,
            version: that.editForm.version,
            storageName: that.editForm.storageName,
            techType: that.editForm.techType,
            totalVolume: that.editForm.totalVolume,
            initTradeVolume: that.editForm.initTradeVolume,
            initTradeTime: that.editForm.initTradeTime,
            initViolateTime: that.editForm.initViolateTime,
            province: that.editForm.province,
            city: that.editForm.city,
            migGrade: that.editForm.migGrade,
            migReference: that.editForm.migReference
          },
          loading: true,
          success: (res) => {
            setTimeout(() => {
              this.$pcNProgress.done();
            }, 300);
            if (res.code === 200) {
              this.successTip('保存成功', 2000);
              that.$emit('sure');
            } else {
              this.errorTip(res.message);
            }
          }
        });
      }
    }
  };
</script>
<style>
  .base-storage-edit-storage-frame {
    display: flex;
    flex-wrap: wrap;
    width: 958px;
    height: 350px;
    border: 1px solid #e5e5e5;
    background-color: white
  }
  .base-storage-edit-storage-frame .el-form-item {
    display: inline-block;
    width: 420px;
    margin-left: 20px;
    margin-right: 20px;
  }
  .base-storage-edit-storage-frame .el-form-item-right {
    float: right;
  }
  .base-storage-edit-storage-inputForm {
    margin-top:10px;
  }
  .base-storage-edit-storage-btnFrame {
    width: 100%;
    margin-top: 40px;
    margin-bottom: 20px;
    text-align: center;
  }
  .base-storage-edit-storage-btn {
    width: 140px;
    height: 40px;
  }
  .base-storage-edit-storage-selector {
    width: 420px;
  }
  .base-storage-edit-storage-city-picker {
    width: 100%;
    display: flex;
    flex-wrap: wrap
  }
</style>
